package com.tructc.vwad

import javax.servlet.ServletContext;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext
import org.springframework.context.ApplicationContextAware
import org.springframework.transaction.annotation.Transactional;

@Transactional
class VideoService implements ApplicationContextAware {
	
	ApplicationContext applicationContext;
	def grailsApplication;

    def boolean upload(video, fileName, meetingID) {
		
		try {
			if(fileName != null && !video.empty)
			{
				def uploadPath = "${grailsApplication.config.myagile.upload.location}"+"/meeting_video"
				File f = new File(uploadPath);
				if(!f.exists())
				{
					f.mkdirs();
				}
				// Prepend meeting id for preventing the file overwriting
				fileName = "id"+meetingID+"_"+fileName;
				// Clean file name for security reason
				fileName = fileName.replaceAll(/[^\w\._]+/,"_");
				
				video.transferTo(new File(f.getPath()+'/'+fileName));
				
				this.addVideo(meetingID,fileName);
				return true;
			} else {
				return false;
			}
			
		} catch(Exception e)
		{
			println("Error: "+e.message);
			return false;
		}
    }
	
	def addVideo(meetingID,fileName)
	{
		Meeting meeting = Meeting.findById(meetingID);
		def video = new Video(filename: fileName);
		meeting.addToVideos(video).save(failOnError : true);
		return video;
	}
	
	
	@Override
	public void setApplicationContext(ApplicationContext ctx)
			throws BeansException {
		this.applicationContext = ctx;
		
	}
	
}
